﻿using SocketBook7Server.db;
using SocketBook7Server.Script.logic;
using SocketBook7Server.Script.net;
using System;
using System.Linq;

//namespace SocketBook7Server.Script.logic
public partial class EventHandler
{
    public static void OnDisconnect(ClientState c)
    {
        Console.WriteLine("OnDisconnect + Close");
        //Player下线
        if (c.player != null)
        {
            //保存数据
            DbManager.UpdatePlayerData(c.player.id, c.player.data);
            //移除
            PlayerManager.RemovePlayer(c.player.id);
        }
    }
    public static void OnTimer()
    {
        CheckPing();
        RoomManager.Update();
    }
    public static void CheckPing()
    {
        //现在的时间戳
        long timeNow = NetManager.GetTimeStamp();
        //遍历，删除
        //lock (NetManager.clients)
        //{
        //    //foreach (ClientState s in clients.Values)
        //    //{
        //    //    checkRead.Add(s.socket);
        //    //}
        //    for (int i = 0; i < NetManager.clients.Count; i++)
        //    {
        //        var s = NetManager.clients.ElementAt(i);
        //        if (s.Value.socket == null)
        //        {
        //            NetManager.Close(s);
        //            return;
        //        }
        //    }
        //}
        foreach (ClientState s in NetManager.clients.Values)
        {
            if (s.lastPingTime > 0)
            {
                s.lastPingTime1 = timeNow;
                if (timeNow - s.lastPingTime > NetManager.pingInterval * 4)
                {
                    //也就是满足这个if条件 然后就由服务端主动关闭了连接
                    Console.WriteLine("timeNow  " + timeNow);
                    Console.WriteLine("timeNow - s.lastPingTime " + (timeNow - s.lastPingTime));
                    Console.WriteLine("NetManager.pingInterval * 4 " + (NetManager.pingInterval * 4));

                    Console.WriteLine("Ping Close " + s.socket.RemoteEndPoint.ToString());
                    NetManager.Close(s);
                    return;
                }
            }
        }
    }
}

